package com.guigu.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.guigu.auth.entity.AuthUser;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guigu.auth.entity.vo.AuthUserVO;
import com.guigu.auth.mapper.AuthUserMapper;
import com.guigu.auth.service.AuthUserService;
import com.guigu.commons.utils.AuthCode;
import com.guigu.commons.utils.JwtUtils;
import com.guigu.tms.exception.TmsException;
import com.guigu.tms.result.R;
import com.guigu.tms.result.ResultCode;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author TaoLong
 * @since 2021-12-06
 */
@Service
public class AuthUserServiceImpl extends ServiceImpl<AuthUserMapper, AuthUser> implements AuthUserService {

    @Override
    public R<AuthUserVO> findByToken(String token) {
        try {
            if (StringUtils.isBlank(token)) {
                throw new TmsException(AuthCode.LOGIN_FAILED_CODE, "令牌为空!");
            }
            if (!JwtUtils.checkToken(token)) {
                throw new TmsException(AuthCode.LOGIN_FAILED_CODE, "会话已过期!");
            }
            String id = JwtUtils.getMemberIdByJwtToken(token);
            AuthUser authUser = this.baseMapper.selectById(Long.valueOf(id));
            if (ObjectUtils.isEmpty(authUser)) {
                throw new TmsException(ResultCode.ERROR_CODE, "信息查询为空!");
            }
            AuthUserVO authUserVO = new AuthUserVO();
            BeanUtils.copyProperties(authUser, authUserVO);
            return new R<>(ResultCode.SUCCESS_CODE, authUserVO);
        } catch (TmsException e) {
            e.printStackTrace();
            throw new TmsException(ResultCode.ERROR_CODE, "令牌解析异常!");
        }
    }

    @Override
    public AuthUser getByOpenId(String openId) {
        if (StringUtils.isBlank(openId)) {
            throw new TmsException(ResultCode.ERROR_CODE, "微信开放Id为空!");
        }
        QueryWrapper<AuthUser> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("open_id", openId);
        return getOne(queryWrapper);
    }
}
